package com.springlearn.springsourcecode.chap12;

import javax.naming.spi.ObjectFactory;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author wtcode
 * @Description
 * @date 2025/3/31 - 15:54
 */
public class JdkProxyDemo {

    interface Foo{
        void foo();
    }

    static class Target implements Foo{

        @Override
        public void foo() {
            System.out.println("target foo");
        }
    }


    public static void main(String[] args) throws IOException {

        Target target = new Target();

        ClassLoader classLoader = JdkProxyDemo.class.getClassLoader(); // 用来加载在运行期间动态生成的字节码
        Foo proxy = (Foo)Proxy.newProxyInstance(classLoader, new Class[]{Foo.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("before...");
                Object result = method.invoke(target, args);
                System.out.println("after...");
                return result;  // 让代理也返回目标方法执行的结果
            }
        });
        System.out.println(proxy.getClass());
        proxy.foo();
        System.in.read();
    }
}
